package org.sundatagroup.aurora.show.controller;

import com.google.gson.JsonObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.sundatagroup.aurora.core.controller.IJsonResultController;
import org.sundatagroup.aurora.show.entity.asset.Asset;
import org.sundatagroup.aurora.show.service.AssetService;

import java.nio.file.Paths;

/**
 * 用于处理图片、SVG 路径等资源的控制器
 * @author Zdream
 * @date 2018-04-23
 * @since 0.1.1
 */
@Controller
public class DisplayAssetController implements IJsonResultController {
	
	@Value("${img.location}")
    private String mImagesPath;

	@Autowired
    private ResourceLoader resourceLoader;
	
	@Autowired
	private AssetService assetService;
	
    private final static Logger LOGGER = LoggerFactory.getLogger(DisplayAssetController.class);
	
	@RequestMapping(method = RequestMethod.GET, value = "/aurora/img/{filename:.+}")  
    @ResponseBody  
	public ResponseEntity<?> getFile(@PathVariable String filename) {
		try {
			Resource res = resourceLoader.getResource("file:" + Paths.get(mImagesPath, filename).toString());
			LOGGER.debug("获取文件位置: " + res);
			return ResponseEntity.ok(res);
		} catch (Exception e) {
			return ResponseEntity.notFound().build();
		}
	}
	
	/**
	 * 根据 name 和 type 来获得资源数据
	 * @param name
	 * @param type
	 * @return 返回 Json 数据
	 */
	@RequestMapping(value = "/aurora/show/do/queryAsset",
			method = RequestMethod.GET,
			produces = {"application/json"})
	@ResponseBody
	public String queryAsset(@RequestParam String name, @RequestParam String type){
		Asset a = assetService.queryByNameAndType(name, type);
		JsonObject json = (a == null) ? rawResultJsonObject(false) : a.toJson();

		return json.toString();
	}

}
